package com.videoStream.video.nginx;


import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.io.*;
import java.util.ArrayList;
import java.util.List;

/**
 * @Author: wwy
 * @Date: 2022/7/5 14:38
 */
@Component
public class NginxService {
    private static final Logger LOGGER = LoggerFactory.getLogger(NginxService.class);
    @Value("${nginxPath}")
    private String nginxPath;

    public void startProc() {
        String nginx = nginxPath+"\\"+"nginx.exe";
        LOGGER.info("开启进程: {}",nginx);
        try {
            ProcessBuilder processBuilder = new ProcessBuilder();
            //通过command方法传入命令，参数有两种，一个是可变参数，另一种是集合，将命令符分开传入或者添加到集合中一起传入均可
            List<String> commandList = new ArrayList<>();
            commandList.add(nginx);
            commandList.add("-c");
            commandList.add(nginxPath+"\\conf\\nginx.conf");
            processBuilder.command(commandList);
            //将标准输入流和错误输入流合并，通过标准输入流读取信息，
            processBuilder.redirectErrorStream(true);
            //执行命令
            Process start = processBuilder.start();
            //获取回显输入流，进行打印输出
            InputStream inputStream = start.getInputStream();
            InputStreamReader inputStreamReader = new InputStreamReader(inputStream, "gbk");
            int len = -1;
            char[] c = new char[1024];
            StringBuilder sb = new StringBuilder();
            while ((len = inputStreamReader.read(c)) != -1){
                sb.append(new String(c, 0, len));
            }
            System.out.println(sb);
        } catch (IOException e) {
            System.err.println("nginx.exe" + "线程开启失败");
            e.printStackTrace();
        }
    }

    /**
     * 获取nginxPid
     */
    public String getNginxPid(){
        String nginxPid = nginxPath+"\\logs\\"+"nginx.pid";
        File nginxPidFil = new File(nginxPid);
        if(!nginxPidFil.exists()){
            return null;
        }
        FileReader file = null;
        BufferedReader buffer = null;
        try {
            file = new FileReader(nginxPidFil);
            buffer = new BufferedReader(file);
            String line = buffer.readLine();
            System.out.println(line);
            buffer.close();
            file.close();
            return line.trim();

        } catch (IOException e) {
            e.printStackTrace();
            if(buffer != null){
                try {
                    buffer.close();
                } catch (IOException e1) {
                    e1.printStackTrace();
                }
            }
            if(file != null){
                try {
                    file.close();
                } catch (IOException e1) {
                    e1.printStackTrace();
                }
            }
        }
        return null;

    }



}
